#include"head.h"
#include"common.h"
#include"ip.h"
struct KernelResponse addNATRule(char *sip,char *natIP,unsigned short minport,unsigned short maxport) {
	struct cmdRequest req;
	struct KernelResponse rsp;
	// form rule
	struct NATRecord rule;
	if(IPstr2IPint(natIP,&rule.daddr,&rule.smask)!=0) {
		// rsp.code = ERROR_CODE_WRONG_IP;
		return rsp;
	}
	if(IPstr2IPint(sip,&rule.saddr,&rule.smask)!=0) {
		// rsp.code = ERROR_CODE_WRONG_IP;
		return rsp;
	}
	rule.sport = minport;
	rule.dport = maxport;
	// form req
	req.tp = REQ_ADDNATRule;
	req.msg.natRule = rule;
	// exchange
	return exMsg(&req, sizeof(req));
}

struct KernelResponse getAllNATRules(void) {
	struct cmdRequest req;
	// exchange msg
	req.tp = REQ_GETNATRules;
	return exMsg(&req, sizeof(req));
}
struct KernelResponse cmdAddNATRule(void) {
	struct KernelResponse empty;
	char saddr[25],daddr[25],port[15];
	unsigned short portMin,portMax;
	
	// printf("ONLY source NAT is supported\n");
	// 源IP
	printf("Please input the src ip and the src mask [like 192.168.64.2/24]: ");
	scanf("%s",saddr);
	// NAT IP
	printf("Please input the NAT ip[like 192.168.152.1]: ");
	scanf("%s",daddr);
	// 目的端口
	printf("Please input the NAT port range [like 10000-30000 or any]: ");
	scanf("%s",port);
	if(strcmp(port, "any") == 0) {
		portMin = 0,portMax = 0xFFFFu;
	} else {
		sscanf(port,"%hu-%hu",&portMin,&portMax);
	}
	if(portMin > portMax) {
		printf("Min > Max. Error.\n");
		return empty;
	}
	return addNATRule(saddr,daddr,portMin,portMax);
}


int showNATRules(struct NATRecord *rules, int len) {
	int i, col = 66;
	char saddr[25],daddr[25];
	if(len == 0) {
		printf("No NAT rules now.\n");
		return 0;
	}
	//printf("NAT rule num: %d\n", len);
	printLine();
	printf("| seq | %18s |->| %-18s | %-11s |\n", "src IP", "NAT IP", "NAT Port");
	printLine();
	for(i = 0; i < len; i++) {
		IPint2IPstr(rules[i].saddr,rules[i].smask,saddr);
		IPint2IPstrNoMask(rules[i].daddr,daddr);
		printf("| %3d | %18s |->| %-18s | %5u~%-5u |\n", i, saddr, daddr, rules[i].sport, rules[i].dport);
		printLine();
	}
	return 0;
}
